<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button type="success" style="margin-bottom: 10px;" @click="ShowAddDialog">添加</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" :icon="Download" circle @click="downloadClass"
           style="margin-right: 20px;margin-left: 15px">
    <el-icon>
        <Download />
    </el-icon>
</el-button>
</el-form-item>
<el-form-item>
<el-upload :on-success="uploadClass" action="http://localhost:8080/admin/cars/upload"
           :headers="headers" method="post" name="file" list-type="none" :show-file-list="false">
    <el-button type="warning" :icon="UploadFilled" circle>
        <el-icon>
            <Upload />
        </el-icon>
    </el-button>
</el-upload>
</el-form-item>

          <el-form-item style="float: right;">
            <el-input v-model="cplate" placeholder="请输入要搜索的车牌号" @input="selectByCplate(1);" style="width: 300px">
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <div style="margin-top: 20px" @change="selectByCplate(1)">
              <el-radio-group v-model="cstate">
                <el-radio value="1" border>出租中</el-radio>
                <el-radio value="2" border>未出租</el-radio>
                <el-radio value="" border>所有车</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>
        <el-table :data="pageInfo.list" border style="width: 100%">
          <el-table-column prop="cid" label="ID" />
          <el-table-column prop="models.mname" label="车型名称" />
          <el-table-column prop="cplate" label="车牌号" />
          <el-table-column prop="cstate" label="租车状态">
            <template #default="scope">
              <span v-if="scope.row.cstate == 1">
                <el-tag type="primary">出租中</el-tag></span>
              <span v-else> <el-tag type="info">未出租</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column prop="brand" label="品牌" />
          <el-table-column prop="eavatar" label="头像">
            <template #default="scope">
              <el-avatar shape="square" :size="50" :src="'http://localhost:8080/upload/' + scope.row.eavatar" />
            </template>
          </el-table-column>
          <el-table-column prop="pirce" label="价格" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="primary" @click="selectByCid(scope.row.cid)">修改</el-button>
              <el-popconfirm title="你确定要删除该车辆吗?" confirm-button-text="确认" cancel-button-text="取消" width="200px"
                @confirm="deleteBycid(scope.row.cid)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="row-bg" justify="center" style="margin-top: 20px;">
          <el-pagination background layout="prev, pager, next" v-model:current-page="pageInfo.pageNum"
            v-model:page-count="pageInfo.pages" @updare:current-page="selectByCplate" />
        </el-row>

      </el-card>
    </el-col>
  </el-row>


  <!-- 添加模态框开始 -->
  <el-dialog v-model="carsAddDialogShow" title="添加车型" width="500px">
    <el-form-item label="车型" lable-width="20%">
      <el-select v-model="carsAdd.mid" placeholder="请选择车型" style="width: 300px">
        <el-option v-for="(models, index) in modelsList" :key="index" :label="models.mname" :value="models.mid" />
      </el-select>
    </el-form-item>
    <el-form>
      <el-form-item label="车牌号" lable-width="20%">
        <el-input v-model="carsAdd.cplate" autocomplete="off" />
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item label="品牌" lable-width="20%">
        <el-input v-model="carsAdd.brand" autocomplete="off" />
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item label="租一天的价格" lable-width="20%">
        <el-input v-model="carsAdd.pirce" autocomplete="off" />
      </el-form-item>
    </el-form>

    <el-form-item label="头像" lable-width="20%">
      <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload" name="pic" :headers="headers"
        :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="carsAddDialogShow = false">取消</el-button>
        <el-button type="primary" @click="insert()"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加模态框结束 -->                    

  <!-- 修改模态框开始 -->
  <el-dialog v-model="carsUpdateDialogShow" title="修改车型" width="500px">
    <el-form-item label="车型" lable-width="20%">
      <el-select v-model="carsUpdate.mid" placeholder="请选择车型" style="width: 300px">
        <el-option v-for="(models, index) in modelsList" :key="index" :label="models.mname" :value="models.mid" />
      </el-select>
    </el-form-item>
    <el-form>
      <el-form-item label="车牌号" lable-width="20%">
        <el-input v-model="carsUpdate.cplate" autocomplete="off" />
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item label="品牌" lable-width="20%">
        <el-input v-model="carsUpdate.brand" autocomplete="off" />
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item label="租一天的价格" lable-width="20%">
        <el-input v-model="carsUpdate.pirce" autocomplete="off" />
      </el-form-item>
    </el-form>
    <el-form-item label="头像" lable-width="20%">
      <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload" name="pic" :headers="headers"
        :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess1">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="carsUpdateDialogShow = false">取消</el-button>
        <el-button type="primary" @click="update()"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改模态框结束 -->

</template>


<script setup>
import { Download, Search, Upload, UploadFilled} from '@element-plus/icons-vue'
import modelsApi from '@/api/modelsApi';
import carsApi from '@/api/carsApi';
import { ElMessage } from 'element-plus';
import { computed, reactive, ref } from 'vue';
import { ElLoading } from 'element-plus'
import { useTokenStore } from '@/stores/token';
const tokenStore = useTokenStore();

const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }


});


// 添加框
const carsAddDialogShow = ref(false);
//修改框
const carsUpdateDialogShow = ref(false);
//所有车型的·
const modelsList = ref([]);
//用来搜索的关键字
const cplate = ref('');
const cstate = ref('');
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
//被添加部门的信息
const carsAdd = ref({
  mid: '',
  cplate: '',
  brand: '',
  eavatar: '',
  pirce: ''
});
//被修改部门的信息
const carsUpdate = ref({
  cid: '',
  mid: '',
  cplate: '',
  brand: '',
  eavatar: '',
  pirce: ''
});
//上传图片的地址
const imageUrl = ref("");

//查询车型并添加到对话框
function ShowAddDialog() {
  modelsApi.selectAll()
    .then(resp => {
      modelsList.value = resp.data;
      //显示添加框
      carsAddDialogShow.value = true
    });

}
//定义方法根据mid查询部门信息
function selectByCid(cid) {
  modelsApi.selectAll()
    .then(resp => {
      modelsList.value = resp.data;
    });
  carsApi.selectByCid(cid)
    .then(resp => {
      carsUpdate.value = resp.data;
      //显示修改框
      carsUpdateDialogShow.value = true;
    });
}
//修改车辆的方法

//定义方法完成部门修改
function update() {
  //开启加载动画
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  carsApi.update(carsUpdate.value)
    .then(resp => {
      loading.close();//取消加载动画
      if (resp.code == 10000) {
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        //隐藏对话框
        carsUpdateDialogShow.value = false;
        //刷新表格数据
        selectByCplate(1);
      } else {
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000,
        });
      }
    });
}

//添加车辆的方法
function insert() {
  //开启加载动画
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  carsApi.insert(carsAdd.value)
    .then(resp => {
      loading.close();//取消加载动画
      if (resp.code == 10000) {
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        //隐藏对话框
        carsAddDialogShow.value = false;
        //清空对话框中的数据
        carsAdd.value = {
          mid: '',
          cplate: '',
          brand: '',
          Price: '',
          eavatar: ''
        }
        imageUrl.value = '';
        //刷新表格数据
        selectByCplate(1);
      } else {
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    });
}

//定义方法删除部门
function deleteBycid(cid) {
  //开启加载动画
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  carsApi.delete(cid)
    .then(resp => {
      loading.close();//取消加载动画
      //判断-- 弹出信息-刷新表格
      if (resp.code == 10000) {
        //弹出信息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        //刷新表格
        selectByCplate(1);
      } else {
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    });
}

//上传图片之前的回调
function beforeAvatarUpload(rawFile) {
  if (rawFile.type != 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2MB!')
    return false
  }
  return true
}
//成功上传之后 的回调
function handleAvatarSuccess(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    imageUrl.value = "http://localhost:8080/upload/" + resp.data;
    carsAdd.value.eavatar = resp.data;
  }
}

function handleAvatarSuccess1(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    imageUrl.value = "http://localhost:8080/upload/" + resp.data;
    carsUpdate.value.eavatar = resp.data;
  }
}
//分页查询；  
function selectByCplate(pageNum) {
  carsApi.selectByCplate(pageNum, cplate.value, cstate.value)
    .then(resp => {
      pageInfo.value = resp.data;
    });
}
function downloadClass() {
   carsApi.download()
        .then(resp => {
            let blob = new Blob([resp], { type: 'application/xlsx' });
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = "车辆表.xlsx";
            link.click();
            URL.revokeObjectURL(url);
        })
}


//上传
function uploadClass(response) {
    if (response.code==10000){
        selectByCplate();
        ElMessage.success("上传成功");
    }else {
        ElMessage.error(response.msg);
    }

}

//默认查询首页
selectByCplate(1);
</script>

<style scoped>
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>